<?php
/**
 * Copyright 2011  SURFfoundation
 * 
 * This file is part of ESCAPE.
 * 
 * ESCAPE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * ESCAPE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with ESCAPE.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * For more information:
 * http://escapesurf.wordpress.com/
 * http://www.surffoundation.nl/
 * 
 * Contact: d.vierkant@utwente.nl
 * 
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3
 */
?>
<?php
/**
 * Process openID login
 * 
 * Process an OpenID login, redirecting either to the return URL or signup page.
 */
class escape_repositoryui_action_ProcessOpenIdLogin extends escape_repositoryui_Action
{
	public function handleRequest()
	{
		/* @var $repository escape_repository_Repository */
		$repository =& $this->requestAttributes['repository'];
		/* @var $repositoryUi escape_repositoryui_RepositoryUi */
		$repositoryUi =& $this->requestAttributes['repositoryUi'];
		
		// check if OpenID is enabled
		if(!$repository->config['localauthn_enabled'] || !$repository->config['openidauthn_enabled'])
		{
			// openid is disabled
			$repositoryUi->displayErrorPage('OpenID is disabled.');
			return null;
		}
		
		$returnUrl = $_REQUEST['return_url'];
		$signupUrl = $repository->config['server_url'] . '/signup?return_url=' . rawurlencode($returnUrl);
		if($repositoryUi->isGadgetMode())
		{
			$signupUrl .= '&gadget=1';
		}
				
		$identityUrl = $_SESSION['openid_identifier'];
		
		// see if any local user is associated to the OpenID specified
		$user = $repository->getUserByOpenId($identityUrl);
		if($user === null)
		{
			// no user found, go to the signup page
			header("Location: " . $signupUrl);
		}
		else
		{
			// user found, add it to the session
			$_SESSION['user_uri'] = $user->getUri();

			header("Location: " . $returnUrl);
		}
		
		return null;
	}
}